<!-- 排期 -->
<template>
  <div class="schedulingBox" v-loading="loading">
    <!-- 需求信息start -->
    <Descriptions
      :title="$i18n.t('mesRequirePlan.demandInformation')"
      :list="requireList"
      :status="statusName"
      :type="statusType"
    />
    <div class="flex-box">
      <Descriptions :list="requireList2" />
    </div>
    <!-- 需求信息end -->
    <div class="goods" v-if="isDefault == 0">
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-width="120px"
        :inline="true"
        :show-message="false"
      >
        <div class="flex">
          <Title :title="$i18n.t('mesRequirePlan.materials')" />
          <div>
            <el-form-item
              :label="$i18n.t('mesRequirePlan.planDeliveryDate')"
              prop="deliveryDate"
              :rules="rules.requireDate"
            >
              <el-date-picker
                v-model="ruleForm.deliveryDate"
                type="date"
                :placeholder="$i18n.t('mesRequirePlan.selectionDate')"
                value-format="yyyy-MM-dd"
                :pickerOptions="{
                  disabledDate: (time) =>
                    time.getTime() < new Date(new Date().setHours(0, 0, 0, 0)),
                }"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item
              :label="$i18n.t('mesRequirePlan.thisTime')"
              prop="scheduledNum"
              :rules="rules.scheduledNum"
            >
              <el-input-number
                v-model="ruleForm.scheduledNum"
                @change="scheduledNumChange"
                :min="1"
                :max="mesRequirePlan.quantity - mesRequirePlan.scheduledNum"
              ></el-input-number>
            </el-form-item>
          </div>
        </div>
        <el-table
          :data="ruleForm.tableData"
          row-key="key"
          border
          default-expand-all
          :tree-props="{
            children: 'childBomStructureList',
            hasChildren: 'hasChildren',
          }"
          height="calc(100vh - 440px)"
        >
        <el-table-column
          :label='$i18n.t("mesRequirePlan.materialRequirements")'
          width="190"
          prop= "prodName"
          header-align="center"
        ></el-table-column>
          <el-table-column
            v-for="(ite, i) in column"
            :key="i"
            align="center"
            :prop="ite.prop"
            :label="ite.label"
            :fixed="ite.fixed || null"
            :width="ite.width || ''"
          >
          </el-table-column>
          <el-table-column
            :label="$i18n.t('mesRequirePlan.planQty')"
            align="center"
            width="120"
            fixed="right"
          >
            <template slot-scope="scope">
              <div
                :class="setColorStyle(scope.row.needQty, scope.row.needQuaity)"
              >
                <span v-if="scope.$index == 0">{{ scope.row.needQty }}</span>
                <el-input-number
                  controls-position="right"
                  v-else
                  :min="0"
                  v-model="scope.row.needQty"
                ></el-input-number>
              </div>
            </template>
          </el-table-column>
          <!-- 车间 -->
          <el-table-column
            :label="$i18n.t('mesRequirePlan.workshop')"
            width="200"
            fixed="right"
            :render-header="addRedStar"
            align="center"
          >
            <template slot-scope="scope">
              <el-form-item
                :prop="'tableData.' + getPropPosi(scope.row) + '.workshopCode'"
                :rules="rules.workshopCode"
              >
                <el-select
                  v-model="scope.row.workshopCode"
                  :placeholder="$t('common.select')"
                  @change="
                    (val) => {
                      workshopSelect(val, scope.row);
                    }
                  "
                  filterable
                >
                  <el-option
                    v-for="item in workshopList"
                    :key="item.modelingCode"
                    :label="item.modelingName"
                    :value="item.modelingCode"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <!-- 线体 -->
          <el-table-column
            :label="$i18n.t('mesRequirePlan.line')"
            width="200"
            align="center"
            fixed="right"
          >
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.lineCode"
                @change="
                  (val) => {
                    lineSelect(val, scope.row);
                  }
                "
                :placeholder="$t('common.select')"
                filterable
              >
                <el-option
                  v-for="item in scope.row.lineList"
                  :key="item.modelingCode"
                  :label="item.modelingName"
                  :value="item.modelingCode"
                >
                </el-option>
              </el-select>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </div>
    <div class="goods" v-if="isDefault == 1">
      <div class="flex">
        <div class="title">
          <div class="icon"></div>
          <div class="text">
            {{ $i18n.t("mesRequirePlan.productionSchedule") }}
          </div>
        </div>
      </div>
      <el-tabs type="border-card">
        <el-tab-pane :label="$i18n.t('mesRequirePlan.sequentialChart')">
          <TimingDiagram
            :data="queryData"
            @changeSlider="changePlanDate"
            height="calc(100vh - 500px)"
          ></TimingDiagram>
        </el-tab-pane>
        <el-tab-pane :label="$i18n.t('mesRequirePlan.list')">
          <el-form
            ref="ruleForm1"
            :model="ruleForm"
            :rules="rules"
            label-width="120px"
            :inline="true"
            :show-message="false"
          >
            <el-table :data="ruleForm.tableData" border height="calc(100vh - 500px)">
              <el-table-column
                v-for="(ite, i) in column2"
                :key="i"
                :prop="ite.prop"
                :label="ite.label"
                align="center"
                :width="ite.width || ''"
              >
              </el-table-column>
              <el-table-column
                :label="$i18n.t('mesRequirePlan.startendDate')"
                width="390"
                align="center"
                fixed="right"
              >
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'tableData.' + scope.$index + '.planDate'"
                    :rules="rules.planDate"
                  >
                    <el-date-picker
                      :clearable="false"
                      @change="
                        (val) =>
                          changePlanDate({ date: val, index: scope.$index })
                      "
                      v-model="scope.row.planDate"
                      type="daterange"
                      :range-separator="$i18n.t('mesRequirePlan.to')"
                      value-format="yyyy-MM-dd"
                      :picker-options="pickerOptions"
                      :start-placeholder="$i18n.t('mesRequirePlan.beginDate')"
                      :end-placeholder="$i18n.t('mesRequirePlan.endDate')"
                    >
                    </el-date-picker>
                  </el-form-item>
                </template>
              </el-table-column>
              <!-- <el-table-column
                label="结束日期"
                width="260"
                align="center"
                fixed="right"
              >
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'tableData.' + scope.$index + '.planEndDate'"
                    :rules="rules.planEndDate"
                  >
                    <el-date-picker
                      v-model="scope.row.planEndDate"
                      type="date"
                      :placeholder="$i18n.t('mesRequirePlan.selectionDate')"
                    >
                    </el-date-picker>
                  </el-form-item>
                </template>
              </el-table-column> -->
              <el-table-column
                prop="workshopName"
                :label="$i18n.t('mesRequirePlan.workshop')"
                width="180"
                align="center"
              >
              </el-table-column>
              <el-table-column
                prop="lineName"
                :label="$i18n.t('mesRequirePlan.line')"
                width="180"
                align="center"
              >
              </el-table-column>
            </el-table>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </div>

    <div class="footer">
      <div class="pack">
        <div
          v-if="isDefault == 0"
          style="text-align: center; padding-top: 10px;"
        >
          <el-button type="primary" @click="submit">{{
            $i18n.t("mesRequirePlan.startSchedule")
          }}</el-button>
        </div>
        <div
          v-if="isDefault == 1"
          style="text-align: center; padding-top: 10px;"
        >
          <el-button type="primary" @click="submitComplete">{{
            $i18n.t("mesRequirePlan.confirmationSchedule")
          }}</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Descriptions from "./components/descriptions.vue";
import Title from "./components/title.vue";
import EleTableEditor from "ele-table-editor";
import TimingDiagram from "./components/timingDiagram.vue";
import {
  getLineCodeList, //查询线体
  getLineCodeListNew,
} from "@/api/order/mesProdOrder";
import {
  confirmNumber,
  getPlanStatusList,
  planSchedule,
  confirmPlan,
} from "@/api/order/mesRequirePlan";
export default {
  name: "",
  components: { Descriptions, Title, EleTableEditor, TimingDiagram },
  data() {
    const _this = this;
    return {
      loading: false,
      lineList: [], // 线体
      workshopList: [], //车间
      queryData: {},
      requireList: [
        {
          label: $i18n.t("mesRequirePlan.demandNumber"),
          prop: "requireCode",
          value: "-",
        },
        {
          label: $i18n.t("common.planDeliveryDate"),
          prop: "deliveryDate",
          value: "-",
        },
        {
          label: $i18n.t("mesRequirePlan.customer"),
          prop: "customerName",
          value: "-",
        },
        // {
        //   label: "生产工厂",
        //   prop:"requireCode",
        //   value: "",
        // },
        {
          label: $i18n.t("mesRequirePlan.createByName"),
          prop: "createByName",
          value: "-",
        },
        {
          label: $i18n.t("common.createTime"),
          prop: "createTime",
          value: "-",
        },
      ],
      requireList2: [
        {
          label: $i18n.t("mesRequirePlan.prodCode"),
          prop: "prodCode",
          value: "-",
        },
        {
          label: $i18n.t("mesRequirePlan.prodName"),
          value: "-",
          prop: "prodName",
        },
        {
          label: $i18n.t("common.quantity"),
          prop: "quantity",
          value: "-",
        },
        {
          label: $i18n.t("mesRequirePlan.scheduledNum"),
          prop: "scheduledNum",
          value: "-",
        },
        {
          label: $i18n.t("common.unit"),
          prop: "unit",
          value: "-",
        },
      ],
      ruleForm: {
        tableData: [],
        scheduledNum: "",
      },
      rules: {
        workshopCode: [
          {
            required: true,
            message: $i18n.t("mesRequirePlan.workshopRequired"),
            trigger: "blur",
          },
        ],
        deliveryDate: [
          {
            required: true,
            message: $i18n.t("mesRequirePlan.requiredDeliveryDate"),
            trigger: "blur",
          },
        ],
        scheduledNum: [
          {
            required: true,
            message: $i18n.t("mesRequirePlan.productionQuantityRequired"),
            trigger: "blur",
          },
        ],
        planDate: [
          {
            required: true,
            message: $i18n.t("mesRequirePlan.selectStartDate"),
            trigger: "change",
          },
        ],
        // planEndDate: [
        //   { required: true, message: "请选择结束日期", trigger: "change" },
        // ],
      },

      column: [
        // {
        //   label: $i18n.t("mesRequirePlan.materialRequirements"),
        //   prop: "prodName",
        // },
        {
          label: $i18n.t("common.materialCode"),
          prop: "prodCode",
          width: 100,
        },
        {
          label: $i18n.t("mesRequirePlan.manufactureMethodValue"),
          prop: "manufactureMethodName",
          width: 90,
        },
        {
          label: $i18n.t("mesRequirePlan.productType"),
          prop: "materialTypeName",
          width: 90,
        },
        {
          label: $i18n.t("common.unit"),
          prop: "unit",
          width: 80,
        },
        {
          label: $i18n.t("mesRequirePlan.bomVersion"),
          prop: "bomVersion",
          width: 100,
        },
        {
          label: $i18n.t("common.quantity"),
          prop: "needQuaity",
          width: 80,
          fixed: "right",
        },
      ],
      column2: [
        {
          label: $i18n.t("common.materialCode"),
          prop: "prodCode",
        },
        {
          label: $i18n.t("common.materialName"),
          prop: "prodName",
        },
        // {
        //   label: $i18n.t('mesRequirePlan.manufactureMethodValue'),
        //   prop: "manufactureMethodName",
        //   width: 90,
        // },
        // {
        //   label: $i18n.t('mesRequirePlan.productType'),
        //   prop: "materialTypeName",
        //   width: 90,
        // },
        {
          label: $i18n.t("common.planQty"),
          prop: "quantity",
          width: 80,
        },
        {
          label: $i18n.t("common.unit"),
          prop: "unit",
          width: 80,
        },
      ],
      options: [],
      statusList: [],
      mesRequirePlan: {},
      statusName: "",
      statusType: "",
      isDefault: 0,
      pickerOptions: {
        disabledDate(time) {
          let { timeData } = _this.queryData;

          if (timeData && timeData.length) {
            let s = timeData.at(0);
            let e = timeData.at(-1);

            return (
              time < new Date(s + " 00:00:00").getTime() ||
              time > new Date(e + " 00:00:00").getTime()
            );
          }
        },

        // if()
      },
    };
  },
  methods: {
    async init() {
      try {
        this.loading = true;
        let id = this.$route.query.id;
        let res = await confirmNumber(id);

        let {
          isDefault,
          mesRequirePlan,
          bomStructure,
          timeList,
          mesRequireOrderPlanPreList,
        } = res.data.result;
        this.isDefault = isDefault;
        this.mesRequirePlan = mesRequirePlan;
        if (isDefault == 0) {
          this.handleList([{ ...bomStructure }]);
        } else {
          this.ruleForm.tableData = mesRequireOrderPlanPreList.map((ite) => {
            let { planBeginDate, planEndDate } = ite;
            let date = new Date();
            ite.planDate = [planBeginDate, planEndDate];
            return ite;
          });
          this.timeList = timeList;

          this.queryData = {
            tableData: mesRequireOrderPlanPreList,
            timeData: timeList,
          };
        }
        this.statusList.forEach((v) => {
          if (v.value == mesRequirePlan.requireStatus) {
            this.statusName = v.description;
          }
        });
        this.statusType =
          mesRequirePlan.requireStatus == "30" ? "info" : "danger";

        this.requireList.map((ite) => {
          ite.value = mesRequirePlan[ite.prop];
        });
        this.requireList2.map((ite) => {
          ite.value = mesRequirePlan[ite.prop];
        });
      } finally {
        this.loading = false;
      }
      // this.$set(this.ruleForm, "tableData", [{ ...bomStructure }])
    },

    async getPlanStatusList() {
      let res = await getPlanStatusList();
      this.statusList = res.data.result;
    },
    // 设置颜色
    setColorStyle(num1, num2) {
      if (num1 > num2) {
        return "color1"; //红
      } else if (num1 == num2) {
        return "color2";
      } else {
        return "color3"; //黄
      }
    },
    handleList(list) {
      this.ruleForm.scheduledNum = list[0].needQty;
      mapTree(list);
      function mapTree(list) {
        list.forEach((v) => {
          v.needQuaity = v.needQty;
          // 有子树继续遍历
          if (
            Array.isArray(v.childBomStructureList) &&
            v.childBomStructureList.length
          ) {
            mapTree(v.childBomStructureList);
          }
        });
      }
      this.$set(this.ruleForm, "tableData", list);
    },
    scheduledNumChange(val) {
      mapTree(this.ruleForm.tableData);
      function mapTree(list) {
        list.forEach((v) => {
          v.needQty = Number(val) * v.singleQty;
          // 有子树继续遍历
          if (
            Array.isArray(v.childBomStructureList) &&
            v.childBomStructureList.length
          ) {
            mapTree(v.childBomStructureList);
          }
        });
      }
    },
    changePlanDate(data) {
      let { index, date } = data;
      //console.log(333, date);
      this.$set(this.ruleForm.tableData[index], "planDate", date);
      this.$set(this.ruleForm.tableData[index], "planBeginDate", date[0]);
      this.$set(this.ruleForm.tableData[index], "planEndDate", date[1]);
    },
    // tablet表头必填加*
    addRedStar(h, { column }) {
      return [
        h("span", { style: "color: red" }, "*"),
        h("span", " " + column.label),
      ];
    },
    // 获取车间
    async getWorkshopData() {
      try {
        const list = await getLineCodeListNew({
          modelingCode: this.$store.getters.factoryCode,
          level: 4,
          modelingType: "0",
        });
        this.workshopList = list.data.result || [];
      } catch (error) {
        console.error(error);
      }
    },
    async workshopSelect(val, row) {
      const workshopCode = val;
      this.workshopList.forEach((v) => {
        if (val == v.modelingCode)
          this.$set(row, "workshopName", v.modelingName);
      });
      this.$set(row, "workshopCode", workshopCode);
      this.$set(row, "lineCode", "");
      this.$set(row, "lineName", "");
      const params = {
        level: 5,
        modelingCode: val,
      };
      const list = await getLineCodeList(params);
      this.$set(row, "lineList", list.data.result || []);
    },
    async lineSelect(val, row) {
      row.lineList.forEach((v) => {
        if (val == v.modelingCode) this.$set(row, "lineName", v.modelingName);
      });
    },
    getPropPosi(row) {
      let posi = this.findPosi(this.ruleForm.tableData, row, "", "");
      return posi;
    },
    // 根据路径获取层级
    findPosi(list, row, posi, current) {
      for (let i = 0; i < list.length; i++) {
        if (list[i].key == row.key) {
          return current + i;
        }
        if (
          list[i].childBomStructureList &&
          list[i].childBomStructureList?.length
        ) {
          posi = this.findPosi(
            list[i].childBomStructureList || [],
            row,
            posi,
            current + i + posi + ".childBomStructureList."
          );
        }
      }
      return posi;
    },
    goback() {
      const { name, path } = this.$route;
      this.$store.commit("SET_DELETE", name);
      this.$store.commit("SET_DELTOPMENUS", { name, path });
      this.$router.back();
    },

    // 开始排期
    submit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.submitSchedule();
        } else {
          this.$message.error($i18n.t("mesRequirePlan.pleaseCompleteInfo"));
          return false;
        }
      });
    },
    submitSchedule() {
      let data = {
        deliveryDate: this.ruleForm.deliveryDate,
        scheduledNum: this.ruleForm.scheduledNum,
        mesRequirePlan: this.mesRequirePlan,
        bomStructure: this.ruleForm.tableData[0],
      };
      this.loading = true;
      planSchedule(data)
        .then((res) => {
          if (res.data.success) {
            this.$message.success($i18n.t("mesRequirePlan.msg1"));
            this.init();
          }
          this.loading = false;
        })
        .catch((err) => {
          this.loading = false;
        });
    },
    // 完成排期
    submitComplete() {
      //console.log(888, this.$refs);
      this.$refs.ruleForm1.validate((valid) => {
        if (valid) {
          this.confirmPlan();
        } else {
          this.$message.error($i18n.t("mesRequirePlan.pleaseCompleteInfo"));
          return false;
        }
      });
    },
    confirmPlan() {
      let data = {
        mesRequirePlan: this.mesRequirePlan,
        mesRequireOrderPlanPreList: this.ruleForm.tableData,
      };
      this.loading = true;
      confirmPlan(data)
        .then((res) => {
          if (res.data.success) {
            this.$message.success($i18n.t("mesRequirePlan.msg3"));
            this.loading = false;
            setTimeout(() => {
              this.goback();
            }, 500);
          }
        })
        .catch((error) => {
          this.loading = false;
        });
    },
  },
  async created() {
    try {
      this.loading = true;
      await this.getPlanStatusList();
      await this.init();
      await this.getWorkshopData();
    } finally {
      this.loading = false;
    }
  },
};
</script>
<style scoped lang="scss">
.schedulingBox {
  padding: 0 10px;

  .image__preview {
    margin-right: 12px;
  }

  .color1 {
    color: #d50e0e;
    /deep/.el-input__inner {
      color: #d50e0e !important;
    }
  }

  .color2 {
    color: #2eac34;
    /deep/.el-input__inner {
      color: #2eac34 !important;
    }
  }

  .color3 {
    color: #e8aa24;
    /deep/.el-input__inner {
      color: #e8aa24 !important;
    }
  }
  .flex-box {
    display: flex;
    align-items: center;
    height: 90px;
    padding-top: 5px;
    border-bottom: 1px solid #dedede;
    border-top: 1px solid #dedede;
  }

  .footer {
    width: 100%;
    // height: 90px;
    // position: relative;

    display: flex;
    justify-content: center;
    align-items: center;
    .pack {
      width: 100%;
      height: 100%;
      // position: fixed;
      // bottom: 0px;
    }
  }
}

.goods {
  padding-top: 15px;

  .title {
    display: flex;
    align-items: center;
    padding: 10px 0;

    .icon {
      width: 4px;
      height: 16px;
      background-color: #00bfa5;
      margin-right: 10px;
    }

    .text {
      font-weight: 800;
    }
  }

  .flex {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  /deep/.el-form-item--small.el-form-item {
    margin-bottom: 0;
  }
}
</style>
